import React, { Component } from 'react'
import {connect} from 'react-redux'
import {CarProduct} from '../types/products'

interface IProps{
    item:CarProduct,
    changeNum:(id:number,num:number) => void,
    changeCheck:(id:number,checked:boolean) => void
}

interface IState{
    changeNum:(id:number,num:number) => void
}

class CarProductItem extends Component <IProps,IState>{
    render() {
        let {title,price,id,num,checked} = this.props.item;
        return (
            <div>
                <input type="checkbox" checked={checked} onChange={() => {this.props.changeCheck(id,!checked)}}/>
                <h4>{title}</h4>
                <span>价格：{price}</span>
                <div>
                    <button onClick={() => {this.changeNum(id,num,true)}}>-</button>
                    <span>{num}</span>
                    <button onClick={() => {this.changeNum(id,num,false)}}>+</button>
                </div>
            </div>
        )
    }

    changeNum = (id:number,num:number,flag:boolean) =>{
        if(flag){
            //减
            if(num > 1){
                num = num-1;
                this.props.changeNum(id,num);
            }
        }else{
            //加
            num = num+1;
            this.props.changeNum(id,num);
        }
    }
}

let stateMapToProps = (state:any) => {
    return {}
}

let dispatchMapToProps = (dispatch:any) => {
    return {
        changeNum(id:number,num:number){
            console.log(id,num)
            dispatch({type:'CHANGE_NUM',num,id})
        },
        changeCheck(id:number,checked:boolean){
            dispatch({type:'CHANGE_CHECK',checked,id})
        }
    }
}

export default connect(stateMapToProps,dispatchMapToProps)(CarProductItem)